# BSD 3-Clause 2023 by Kevin Bloom.

BEGIN {
  if(type == "weekly") {
    split("31 28 31 30 31 30 31 31 30 31 30 31", days, " ")
    month = 1
    day = 1
    for(week = 1; week < 53; week++) {
      if (days[month] < day) {
        day -= days[month]
        month++
      }
      weekly[week] = (month < 10 ? "0" month : month) "-" (day < 10 ? "0" day : day)
      day += 6
      if (days[month] < day) {
        day -= days[month]
        month++
      }
      weekly[week] = weekly[week] " -> " (month < 10 ? "0" month : month) "-" (day < 10 ? "0" day : day)
      day++
    }
    if(day <= days[month]) {
      weekly[53] = (month < 10 ? "0" month : month) "-" (day < 10 ? "0" day : day)
      day = days[month]
      weekly[53] = weekly[53] " -> " (month < 10 ? "0" month : month) "-" (day < 10 ? "0" day : day)
    }
  }
  skip = FALSE
}
/;;/ {
  next
}

# check if it might be a date and is definitely not an entry
$1 ~ "-" || $1 ~ "/", $1 == "\n" {
  cor = $1
  if(cor ~ "/") {
    gsub("/", "-", cor);
    phase = "DATE"
    isDate = 0
    skip = 0
  }
  if(cor ~ /[0-9]{4}-[0-9]{2}-[0-9]{2}/) {
    isDate = 1;
    phase = "DATE"
    total = 0
    skip = 0
  }
  split(cor, arr, "-")
  if(!skip) {
    if(phase == "DATE") {
     if(isDate) {
        if(start_date != "" && $1 < start_date) {
          skip = 1
        } else if(end_date != "" && $1 > end_date) {
          exit 0
        } else {
        if(type == "monthly") {
          month = arr[1] "-" arr[2]
          if(length(map[month]) == 0)
            map[month] = month
          entry = month
        } else if(type == "weekly") {
          for(i in weekly) {
            split(weekly[i], dates, " -> ")
            start = dates[1]
            split(start, s, "-")
            end = dates[2]
            split(end, e, "-")
            if(arr[2] >= s[1] &&
               arr[2] <= e[1] &&
               arr[3] >= s[2] &&
               arr[3] <= e[2]) {
              if(length(map[weekly[i]]) == 0)
                map[weekly[i]] = weekly[i]
              entry = weekly[i]
              break;
            }
          }
        } else {
          map[$0] = cor " " substr($0, 12)
          entry = $0
        }
        phase = "ENTRIES"
        }
      } else {
        print "Error with date on line " NR ": " $0
        error = 1
    }
    } else if(!skip && phase == "ENTRIES") {
      isDate = 0;
      map[entry] = map[entry] "<<>>" $0
    }
  }
}
END {
  if(error)
    exit 1
  for(i in map) {
    print map[i]
  }
}
